<template>
    <div>
        <a-modal v-model:visible="visible" width="1000px" title="新增产品需求" :maskClosable="false">
            <div class="modal-wrap">
                <a-form layout="inline" ref="ruleFormRef" :model="form" :rules="rules">
                    <a-row :gutter="24">
                        <a-col :span="24">
                            <a-form-item label="需求标题" name="requireName">
                                <a-textarea v-model:value="form.requireName" placeholder="请输入需求标题限制200个字" :maxlength="200" auto-size />
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item label="所属产品" name="requireSystem">
                                <div style="width: 100%">
                                    <!-- {{ $filters.valToNameFilter('fromSystem', form.requireSystem) }} -->
                                    <h-search-select-cell
                                        type="findUpDownBySystemOrCatalogCode"
                                        label="systemName"
                                        keyField="catalogCode"
                                        :default-value="requestCatalogCode || ''"
                                        :searchQuery="{ catalogCode: requestCatalogCode, isUp: 0 }"
                                        @success="handleSelectChange($event, 'requireCatalogCode')"
                                    />
                                </div>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item label="当前处理人" name="agentUser">
                                <div style="width: 100%">
                                    <h-search-select-cell
                                        type="systemManager"
                                        label="empName"
                                        :default-value="form.agentUser || ''"
                                        :searchQuery="{ catalogCode: form.catalogCode }"
                                        @success="handleSelectChange($event, 'systemManager')"
                                    />
                                </div>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item label="关联业务需求" name="relateRequireName">
                                <div style="width: 100%">{{ form.relateRequireName }}</div>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item label="修复版本">
                                <a-textarea v-model:value="form.repairVersion" placeholder="请输入版本限制150个字" :maxlength="150" auto-size />
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item label="预发布版本" name="relateVersionName">
                                <flexbox>
                                    <flexbox-item>
                                        <h-search-select-cell
                                            ref="searchVersionSelectCellRef"
                                            :default-value="{
                                                label: `${form.relateVersionName ? form.relateVersionName + '-' + form.relateVersionNumber : ''}`,
                                                id: form.relateVersionId
                                            }"
                                            type="version"
                                            keyField="id"
                                            valueLabelField="label"
                                            :searchQuery="{ system: form.requireSystem }"
                                            @success="handleSelectChange($event, 'version')"
                                        >
                                            <template #label="{ record }"> {{ record.versionName }}—{{ record.versionNumber }} </template>
                                        </h-search-select-cell>
                                    </flexbox-item>
                                    <div class="warning-color cursor-pointer margin-l-8" @click="handleCreateVersion">新增版本</div>
                                </flexbox>
                            </a-form-item>
                        </a-col>
                        <a-col :span="12">
                            <a-form-item label="需求类型" name="requireType">
                                <div style="width: 100%">
                                    <a-select placeholder="请选择" v-model:value="form.requireType">
                                        <a-select-option v-for="item of dicOptions.requireType" :key="item.code">
                                            {{ item.dimensionName }}
                                        </a-select-option>
                                    </a-select>
                                </div>
                            </a-form-item>
                        </a-col>

                        <a-col :span="16">
                            <a-form-item label="需求描述" name="requireDesc">
                                <div style="position: relative">
                                    <t-editor v-model="form.requireDesc" />
                                </div>
                            </a-form-item>
                        </a-col>
                        <a-col :span="8">
                            <a-row>
                                <a-col :span="24">
                                    <a-form-item label="开发类型" name="devType">
                                        <span v-if="form.systemType !== '3'">
                                            {{ $filters.valToNameFilter('systemType', form.devType) }}
                                        </span>
                                        <a-select placeholder="请选择" v-model:value="form.devType" style="text-align: left" v-else>
                                            <a-select-option v-for="item of dicOptions.systemType.slice(0, 2)" :key="item.code">
                                                {{ item.dimensionName }}
                                            </a-select-option>
                                        </a-select>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="24">
                                    <a-form-item label="前端预估工时" name="frontPlanWorkHours">
                                        <a-input-number
                                            v-model:value="form.frontPlanWorkHours"
                                            :min="0"
                                            :max="10000"
                                            :maxlength="5"
                                            style="width: 100%"
                                            @change="handleCalcPlanWorkHours"
                                        />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="24">
                                    <a-form-item label="后端预估工时" name="backPlanWorkHours">
                                        <a-input-number
                                            v-model:value="form.backPlanWorkHours"
                                            :min="0"
                                            :max="10000"
                                            :maxlength="5"
                                            style="width: 100%"
                                            @change="handleCalcPlanWorkHours"
                                        />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="24">
                                    <a-form-item label="实施预估工时" name="executePlanWorkHours">
                                        <a-input-number
                                            v-model:value="form.executePlanWorkHours"
                                            :min="0"
                                            :max="10000"
                                            :maxlength="5"
                                            style="width: 100%"
                                            @change="handleCalcPlanWorkHours"
                                        />
                                    </a-form-item>
                                </a-col>
                                <a-col :span="24">
                                    <a-form-item label="预计工时（h）" name="planWorkHours">
                                        <span>{{ form.planWorkHours }}</span>
                                    </a-form-item>
                                </a-col>
                                <a-col :span="24" v-if="form.devType === '1'">
                                    <a-form-item label="计算方式">
                                        <a-radio-group v-model:value="form.calModel" @change="handleRadioChange" style="margin-bottom: 8px">
                                            <a-radio value="0"> 功能点 </a-radio>
                                            <a-radio value="1"> 模块 </a-radio>
                                        </a-radio-group>
                                    </a-form-item>
                                    <div v-if="form.calModel === '0'">
                                        <a-form-item label="人天价格">
                                            <a-input-number v-model:value="form.unitPrice" :min="0" :max="1000000" style="width: 100%" />
                                        </a-form-item>
                                        <a-form-item label="人天数">
                                            <a-input-number v-model:value="form.manDay" :min="0" :max="1000" style="width: 100%" />
                                        </a-form-item>
                                        <a-form-item label="预估成本">
                                            {{ form.unitPrice * form.manDay }}
                                        </a-form-item>
                                    </div>
                                    <div v-else>
                                        <a-form-item label="预估成本">
                                            <a-input-number
                                                v-model:value="form.planCost"
                                                :min="0"
                                                :max="100000000"
                                                :maxlength="9"
                                                style="width: 100%"
                                            />
                                        </a-form-item>
                                    </div>
                                </a-col>
                            </a-row>

                            <a-row v-if="form.devType === '1'">
                                <!-- 供应商 必须是外采系统 -->
                                <a-col :span="24">
                                    <a-form-item label="供应商名称">
                                        <div style="width: 100%">
                                            <a-input v-model:value="form.supplierName" placeholder="请输入名称限制200字以内" :maxlength="200" />
                                        </div>
                                    </a-form-item>
                                    <a-form-item label="供应商平台编号">
                                        <div style="width: 100%">
                                            <a-input v-model:value="form.supplierNum" placeholder="请输入编号限制200字以内" :maxlength="200" />
                                        </div>
                                    </a-form-item>
                                    <a-form-item label="供应商状态">
                                        <div style="width: 100%">
                                            <a-select placeholder="请选择" v-model:value="form.supplierStatus">
                                                <a-select-option v-for="item of dicOptions.supplierStatus" :key="item.code">
                                                    {{ item.dimensionName }}
                                                </a-select-option>
                                            </a-select>
                                        </div>
                                    </a-form-item>
                                </a-col>
                            </a-row>

                            <a-form-item label="标签">
                                <HSearchMultiSelectCell
                                    type="systemLabel"
                                    label="name"
                                    valueLabelField="name"
                                    keyField="name"
                                    isSupportEnter
                                    :disabled="!form.requireSystem"
                                    :default-value="form.pmpLabels"
                                    :searchQuery="{ systemId: form.requireSystem, type: 3 }"
                                    @success="handleSelectChange($event, 'label')"
                                />
                            </a-form-item>
                            <a-form-item label="预计交付日期">
                                <div style="width: 100%">
                                    {{ $filters.dateFilter(form.expectTime) }}
                                </div>
                            </a-form-item>
                            <a-form-item label="上线日期">
                                <div style="width: 100%">
                                    {{ form.onlineTime }}
                                </div>
                            </a-form-item>
                            <a-form-item label="优先级" name="level">
                                <a-select placeholder="请选择" v-model:value="form.level" style="text-align: left">
                                    <a-select-option v-for="item of dicOptions.level" :key="item.code">
                                        {{ item.dimensionName }}
                                    </a-select-option>
                                </a-select>
                            </a-form-item>
                            <a-form-item label="文档">
                                <upload-cell
                                    :span="24"
                                    :fileParams="{ connectType: '产品文档', type: 3 }"
                                    @valueChange="fileChange"
                                    :fileList="form.selfRequestFiles"
                                />
                            </a-form-item>
                        </a-col>
                        <a-col :span="16">
                            <a-form-item label="理由" name="reason">
                                <div style="position: relative; margin-top: 6px">
                                    <a-textarea v-model:value="form.reason" showCount :maxlength="100" auto-size />
                                </div>
                            </a-form-item>
                        </a-col>
                        <a-col :span="16">
                            <a-form-item label="验收标准" name="checkStandard">
                                <div style="position: relative; margin-top: 6px">
                                    <a-textarea v-model:value="form.checkStandard" showCount :maxlength="100" auto-size />
                                </div>
                            </a-form-item>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
            <template #footer>
                <flexbox justify="flex-end" class="btn-group">
                    <a-button @click="visible = false">取消</a-button>
                    <a-button type="primary" @click="handleSubmit">保存</a-button>
                </flexbox>
            </template>
        </a-modal>
        <create-version ref="createVersionRef" @success="createVersionSuccess" />
    </div>
</template>

<script lang="ts">
import { message } from 'ant-design-vue';
import { HSearchSelectCell, HSearchMultiSelectCell, UploadCell } from '@/components';
import CreateVersion from '@/views/version/versionList/components/CreateVersion.vue';
import api from '@/api';
import store from '@/store';
import { useProductFormData, useCreateProductForm } from '@/views/productRequire/createProductRequire/hooks';
import { defineComponent, ref, unref, computed, defineAsyncComponent } from 'vue';
export default defineComponent({
    name: 'CreateStory',
    components: {
        TEditor: defineAsyncComponent(() => import('@/components/TEditor/index.vue')),
        HSearchSelectCell,
        HSearchMultiSelectCell,
        UploadCell,
        CreateVersion
    },
    props: {
        detail: { type: Object, default: () => ({}) }
    },
    emits: ['success'],
    setup(props, { emit }) {
        const { form, setForm, resetForm } = useProductFormData();
        const { createVersionRef, searchVersionSelectCellRef, handleCreateVersion, createVersionSuccess, fileChange, handleSelectChange } =
            useCreateProductForm(form, setForm);
        const ruleFormRef = ref<any>();
        const visible = ref(false);
        const requestCatalogCode = ref<any>('');
        // 监测名称重复
        const validateRepeat = async (rule: any, value: any) => {
            if (value) {
                const { success } = await api.productRequireModel.validProductRepeat({
                    requireName: value,
                    id: null,
                    requireSystem: form.value.requireSystem
                });
                return success ? Promise.reject('需求名称重复') : Promise.resolve();
            } else {
                return Promise.reject('需求名称不能为空');
            }
        };
        const rules = {
            requireName: [
                { required: true, message: '需求标题不能为空', trigger: 'blur' },
                {
                    validator: validateRepeat,
                    message: '需求名称重复'
                }
            ],
            requireType: [{ required: true, message: '需求类型不能为空', trigger: 'blur' }],
            requireDesc: [{ required: true, message: '需求描述不能为空', trigger: 'blur' }],
            level: [{ required: true, message: '优先级不能为空', trigger: 'blur' }],
            agentUser: [{ required: true, message: '当前处理人不能为空', trigger: 'blur' }]
        };
        const handleSubmit = () => {
            unref(ruleFormRef)
                .validate()
                .then(() => {
                    handleSave();
                })
                .catch((err) => {
                    console.log(err);
                });
        };
        const handleSave = async () => {
            const { orgList, name: createUser, empId: createUserEmpId } = store.getters.userInfo.employeeDTO;
            const query = {
                ...unref(form),
                createUser,
                createUserEmpId,
                initiatorDept: orgList[0].name,
                planWorkHours: unref(form).backPlanWorkHours + unref(form).frontPlanWorkHours + unref(form).executePlanWorkHours
            };
            const { success, errorMsg } = await api.productRequireModel.save(query);
            if (success) {
                message.success('创建成功');
                emit('success');
                visible.value = false;
            } else {
                message.error(errorMsg);
            }
        };
        const init = (initForm = {}) => {
            const { id, requestName, requestSystem, pmpProductDetailDTO } = props.detail;
            setForm({
                relateRequireId: id,
                relateRequireName: requestName,
                requireSystem: +requestSystem,
                catalogCode: pmpProductDetailDTO.catalogCode,
                ...initForm
            });
            requestCatalogCode.value = pmpProductDetailDTO.catalogCode;
        };
        // 用来表示是否支持编辑所属系统，当没有选择关联业务时处于可编辑状态
        const requireSystemDisabled = computed((): boolean => {
            return !form.value.requireSystem;
        });
        const handleRadioChange = (e) => {
            const val = e.target.value;
            if (val === '0') {
                setForm({
                    unitPrice: 0
                });
            } else {
                setForm({
                    unitPrice: 0,
                    manDay: 0,
                    planCost: 0
                });
            }
        };
        const handleCalcPlanWorkHours = () => {
            const { backPlanWorkHours, frontPlanWorkHours, executePlanWorkHours } = form.value;
            const planWorkHours = backPlanWorkHours + frontPlanWorkHours + executePlanWorkHours;
            setForm({
                planWorkHours
            });
        };
        const open = (initForm = {}) => {
            visible.value = true;
            resetForm();
            init(initForm);
        };
        return {
            ruleFormRef,
            createVersionRef,
            searchVersionSelectCellRef,
            visible,
            requestCatalogCode,
            rules,
            form,
            handleCreateVersion,
            createVersionSuccess,
            fileChange,
            handleSelectChange,
            handleSubmit,
            open,
            resetForm,
            requireSystemDisabled,
            handleCalcPlanWorkHours,
            handleRadioChange
        };
    }
});
</script>
<style lang="less">
.modal-wrap {
    max-height: 400px;
    overflow-x: hidden;
    overflow-y: auto;
    .ql-snow .ql-picker {
        line-height: 20px !important;
    }
}
</style>
<style scoped lang="less">
.btn-group {
    button + button {
        margin-left: 8px;
    }
}
</style>
